<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\ArticleModel as Article;

class ArticleController extends Controller {


	/**
	 * 首页
	 */
	public function index() {
		$news = Article::paginate(10);
		return view('admin/news/index', array(
			'news' => $news
		));
	}

	/**
	 * 创建
	 */
	public function create() {

		return view('admin/news/add', [
			'action' => 'add',
		]);
	}

	/**
	 * 添加
	 */
	public function store(Request $request) {

		$this->validate($request, [
			'title'   => 'required|unique:articles|max:255',
			'content' => 'required'
		]);

		$news          = new Article();
		$news->title   = $request->input('title');
		$news->content = $request->input('content');

		if ($news->save()) {
			return response()->json([
				'message' => '保存成功',
				'status'  => 1,
				'url'     => url('admin/news')
			]);
		} else {
			return response()->json(['message' => '保存失败', 'status' => 0]);
		}

	}

	/**
	 * 编辑
	 */
	public function edit($id) {

		$data = Article::find($id);

		return view('admin/news/add', [
			'data'   => $data,
			'action' => 'update',
		]);
	}

	/**
	 * 更新
	 */
	public function update(Request $request,$id) {

		$this->validate($request, [
			'title'   => 'required|unique:articles|max:255',
			'content' => 'required',
			'id'      => 'numeric'
		]);

		$data          = Article::find($id);
		$data->title   = $request->input('title');
		$data->content = $request->input('content');

		if ($data->save()) {
			return response()->json([
				'message' => '保存成功',
				'status'  => 1,
				'url'     => url('admin/news')
			]);
		} else {
			return response()->json(['message' => '保存失败', 'status' => 0]);
		}

	}


	/**
	 * 删除
	 */
	public function destroy($id) {

		$data = Article::find($id);

		if ($data->delete()) {
			return response()->json([
				'message' => '删除成功',
				'status'  => 1,
			]);
		} else {
			return response()->json([
				'message' => '删除失败',
				'status'  => 0,
			]);
		}
	}

}
